﻿using Microsoft.AspNetCore.Mvc;
using Qy.Core;
using Qy.Scenario;
using Qy.Web.Authorize;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Qy.Web.Areas.Api;

[Route("Api/[controller]/[action]")]
[Verify]
public class DictDataController : Base
{
    private readonly DictDataService _dictDataService;
    private readonly DictCatService _dictCatService;
    public DictDataController(DictDataService dictDataService, DictCatService dictCatService)
    {
        _dictDataService = dictDataService;
        _dictCatService = dictCatService;
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_Index)]
    public async Task<IActionResult> IndexAsync([FromQuery] QueryDictData query)
    {
        PagedInfo<ViewDictData> pagedList = await _dictDataService.GetPageListAsync(query);
        return Success(new { count = pagedList.TotalNum, data = pagedList.Result });
    }
    [HttpGet]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_AddOrEditView)]
    public async Task<IActionResult> AddOrEditAsync(int id)
    {
        IEnumerable<DictCat> catList = await _dictCatService.GetListAsync();
        DictData data = await _dictDataService.GetIdAsync(id);
        return Success(new { data, catList });
    }
    [HttpPost, ActionName("Create")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_AddOrEdit)]
    [Log(Name = "新增字典")]
    public async Task<IActionResult> CreatePostAsync([FromBody] DictData dictData)
    {
        if (await _dictDataService.InsertDelCache(dictData))
            return Success("新增字典: " + dictData.Key);
        else
            return Fail("新增失败！");
    }
    [HttpPut, ActionName("Edit")]
    [ModelStateFilter]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_AddOrEdit)]
    [Log(Name = "修改字典")]
    public async Task<IActionResult> EditPostAsync([FromBody] DictData dictData)
    {
        if (await _dictDataService.UpdateDelCache(dictData) > 0)
            return Success("成功修改字典 ID：" + dictData.Key);
        else
            return Fail("修改失败");
    }
    [HttpDelete]
    [ActionPermissionFilter(Permission = PermissionKeys.Dict_Delete)]
    [Log(Name = "删除字典")]
    public async Task<IActionResult> Delete(int id)
    {
        if (await _dictDataService.DeleteAsync(id) > 0)
            return Success("删除字典 ID：" + id);
        else
            return Fail("删除失败！");
    }
}
